package com.droid.mvvmlib.livedatabus;

import android.os.Handler;
import android.os.Looper;

import com.droid.mvvmlib.log.Logcat;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.ArrayMap;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

/**
 * LiveDataBus
 *
 * @author zhy0617
 * @since  2019/8/3 18:09
 */
public class LiveDataBus {

    private static final String TAG = "LiveDataBus";

    private static LiveDataBus instance;
    private Map<String, MyMutableLiveData<Object>> mLiveDataArrayMap = new ArrayMap<>();
    private final Stack<Object> observableStack = new Stack<>();

    private LiveDataBus(){

    }

    public static LiveDataBus getInstance(){
        if (instance == null) {
            synchronized (LiveDataBus.class) {
                if(instance == null) {
                    instance = new LiveDataBus();
                }
            }
        }
        return instance;
    }


    public <T> MyMutableLiveData<T> with(String key, Class<T> type) {

        if (!mLiveDataArrayMap.containsKey(key)) {
            mLiveDataArrayMap.put(key, new MyMutableLiveData<Object>());
        }
        return (MyMutableLiveData<T>) mLiveDataArrayMap.get(key);
    }

    public MyMutableLiveData with(String key) {
        return with(key, Object.class);
    }

    public <T> void post(String key, T t) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            with(key).setValue(t);
        } else {
            with(key).postValue(t);
        }
    }

    public Stack<Object> getObservableStack() {
        return observableStack == null ? new Stack<>() : observableStack;
    }

    private static class ObserverWrapper<T> implements Observer<T> {

        private Observer<T> observer;

        public ObserverWrapper(Observer<T> observer) {
            this.observer = observer;
        }

        @Override
        public void onChanged(@Nullable T t) {
            if (observer != null) {
                if (isCallOnObserve()) {
                    return;
                }
                observer.onChanged(t);
            }
        }

        private boolean isCallOnObserve() {
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            if (stackTrace != null && stackTrace.length > 0) {
                for (StackTraceElement element : stackTrace) {
                    if ("android.arch.lifecycle.LiveData".equals(element.getClassName()) &&
                            "observeForever".equals(element.getMethodName())) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    public static class MyMutableLiveData<T> extends MutableLiveData<T> {

        private class PostValueTask implements Runnable {
            private Object newValue;

            public PostValueTask(@NonNull Object newValue) {
                this.newValue = newValue;
            }

            @Override
            public void run() {
                setValue((T) newValue);
            }
        }

        private Map<Observer, Observer> observerMap = new HashMap<>();
        private Handler mainHandler = new Handler(Looper.getMainLooper());

        @Override
        public void postValue(T value) {
            mainHandler.post(new PostValueTask(value));
        }

        @Override
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
            super.observe(owner, observer);
            try {
                hook(observer);
            } catch (Exception e) {
                Logcat.e(TAG, "live data hook fail");
                e.printStackTrace();
            }
        }

        /**
         * 处理粘性事件
         * @param owner
         * @param observer
         */
        public void observeSticky(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
            super.observe(owner, observer);
        }

        @Override
        public void observeForever(@NonNull Observer<? super T> observer) {
            if (!observerMap.containsKey(observer)) {
                observerMap.put(observer, new ObserverWrapper(observer));
            }
            super.observeForever(observerMap.get(observer));
        }

        public void observeStickyForever(@NonNull Observer<T> observer) {
            super.observeForever(observer);
        }

        @Override
        public void removeObserver(@NonNull Observer<? super T> observer) {
            Observer realObserver = null;
            if (observerMap.containsKey(observer)) {
                realObserver = observerMap.remove(observer);
            } else {
                realObserver = observer;
            }
            super.removeObserver(realObserver);
        }

        private void hook(@NonNull Observer<? super T> observer) throws Exception {
            Class<LiveData> liveDataClass = LiveData.class;
            Field fieldObservers = liveDataClass.getDeclaredField("mObservers");
            fieldObservers.setAccessible(true);
            Object mObservers = fieldObservers.get(this);
            Class<?> classObservers = mObservers.getClass();

            Method methodGet = classObservers.getDeclaredMethod("get", Object.class);
            methodGet.setAccessible(true);
            Object objectWrapperEntry = methodGet.invoke(mObservers, observer);
            Object objectWrapper = ((Map.Entry)objectWrapperEntry).getValue();
            Class<?> classObserverWrapper = objectWrapper.getClass().getSuperclass();

            Field fieldLastVersion = classObserverWrapper.getDeclaredField("mLastVersion");
            fieldLastVersion.setAccessible(true);
            Field fieldVersion = liveDataClass.getDeclaredField("mVersion");
            fieldVersion.setAccessible(true);
            Object objectVersion = fieldVersion.get(this);
            fieldLastVersion.set(objectWrapper, objectVersion);
        }
    }
}
